<template>
  <div id="addPicturePage">
    <!--    标题-->
    <!--    <h2>-->
    <!--      {{ route.query?.id ? '编辑图片信息' : '上传图片信息' }}-->
    <!--    </h2>-->
    <a-typography-paragraph v-if="spaceId" type="secondary">
      保存至私有空间：<a :href="`/space/${spaceId}`">{{ spaceId }} </a>
    </a-typography-paragraph>
    <!-- 选择上传方式 -->
    <a-tabs v-model:activeKey="uploadType">
      <a-tab-pane key="file" tab="文件上传">
        <div class="upload-form-container" :class="{ 'has-picture': picture }">
          <div class="upload-section">
            <PictureUpload :picture="picture" :spaceId="spaceId" :onSuccess="onSuccess" />
          </div>
          <div v-if="picture" class="edit-form">
            <a-form
              name="pictureForm"
              layout="vertical"
              :model="pictureForm"
              @finish="handleSubmit"
            >
              <a-form-item name="name" label="图片名称">
                <a-input v-model:value="pictureForm.name" placeholder="请输入图片名称" />
              </a-form-item>
              <a-form-item name="introduction" label="图片简介">
                <a-textarea
                  v-model:value="pictureForm.introduction"
                  placeholder="请输入图片简介"
                  :auto-size="{ minRows: 2, maxRows: 5 }"
                />
              </a-form-item>
              <a-form-item name="category" label="分类">
                <a-auto-complete
                  :options="categoryOptions"
                  v-model:value="pictureForm.category"
                  placeholder="请输入分类"
                  allowClear
                />
              </a-form-item>
              <a-form-item name="tags" label="标签">
                <a-select
                  :options="tagOptions"
                  v-model:value="pictureForm.tags"
                  mode="tags"
                  placeholder="请输入标签"
                  allowClear
                />
              </a-form-item>
              <a-form-item>
                <a-button type="primary" html-type="submit" style="width: 100%">
                  {{ route.query?.id ? '编辑图片信息' : '上传图片信息' }}
                </a-button>
              </a-form-item>
            </a-form>
          </div>
        </div>
      </a-tab-pane>
      <a-tab-pane key="url" tab="URL 上传" force-render>
        <div class="upload-form-container" :class="{ 'has-picture': picture }">
          <div class="upload-section">
            <UrlPictureUpload :picture="picture" :spaceId="spaceId" :onSuccess="onSuccess" />
          </div>
          <div v-if="picture" class="edit-form">
            <a-form
              name="pictureForm"
              layout="vertical"
              :model="pictureForm"
              @finish="handleSubmit"
            >
              <a-form-item name="name" label="图片名称">
                <a-input v-model:value="pictureForm.name" placeholder="请输入图片名称" />
              </a-form-item>
              <a-form-item name="introduction" label="图片简介">
                <a-textarea
                  v-model:value="pictureForm.introduction"
                  placeholder="请输入图片简介"
                  :auto-size="{ minRows: 2, maxRows: 5 }"
                />
              </a-form-item>
              <a-form-item name="category" label="分类">
                <a-auto-complete
                  :options="categoryOptions"
                  v-model:value="pictureForm.category"
                  placeholder="请输入分类"
                  allowClear
                />
              </a-form-item>
              <a-form-item name="tags" label="标签">
                <a-select
                  :options="tagOptions"
                  v-model:value="pictureForm.tags"
                  mode="tags"
                  placeholder="请输入标签"
                  allowClear
                />
              </a-form-item>
              <a-form-item>
                <a-button type="primary" html-type="submit" style="width: 100%">
                  {{ route.query?.id ? '编辑图片信息' : '上传图片信息' }}
                </a-button>
              </a-form-item>
            </a-form>
          </div>
        </div>
      </a-tab-pane>
    </a-tabs>

    <div v-if="picture" class="edit-bar">
      <a-space size="middle">
        <a-button :icon="h(EditOutlined)" @click="doEditPicture"> 裁剪图片 </a-button>
        <a-button type="primary" ghost :icon="h(FullscreenOutlined)" @click="doImagePainting">
          AI 扩图
        </a-button>
      </a-space>
      <ImageCropper
        ref="imageCropperRef"
        :imageUrl="picture?.url"
        :picture="picture"
        :spaceId="spaceId || picture?.spaceId"
        :space="space"
        :onSuccess="onCropSuccess"
      />
      <TaskPainting
        ref="imageOutPaintingRef"
        :picture="picture"
        :spaceId="spaceId || picture?.spaceId"
        :onSuccess="onImageOutPaintingSuccess"
      />
    </div>
  </div>
</template>
<script setup lang="ts">
import { computed, h, onMounted, reactive, ref, watchEffect } from 'vue'
import PictureUpload from '@/components/PictureUpload.vue'
import { useRoute } from 'vue-router'
import { EditOutlined, FullscreenOutlined } from '@ant-design/icons-vue'
import {
  allListPictureTagCategoryUsingGet,
  editPictureUsingPost,
  getPictureVoByIdUsingGet,
  listPictureTagCategoryUsingGet
} from "@/api/pictureController.ts";
import { message } from 'ant-design-vue'
import router from '@/router'
import UrlPictureUpload from '@/components/UrlPictureUpload.vue'
import ImageCropper from '@/components/ImageCropper.vue'
import TaskPainting from '@/components/TaskPainting.vue'
import { getSpaceVoByIdUsingGet } from '@/api/spaceController.ts'

//参数定义
const picture = ref<API.PictureVO>()
const pictureForm = reactive<API.PictureEditRequest>({})
const categoryOptions = ref<String[]>([])
const tagOptions = ref<String[]>([])
const uploadType = ref<'file' | 'url'>('file')

//获取上传图片信息
const onSuccess = (newPicture: API.PictureVO) => {
  picture.value = newPicture
  pictureForm.name = newPicture.name
}
//空间id
const spaceId = computed(() => {
  return route.query?.spaceId
})
//获取分类和标签选项
const getTagCateGoryOptions = async () => {
  const res = await allListPictureTagCategoryUsingGet()
  try {
    if (res.data.code === 0 && res.data.data) {
      //原数据为json，需要转换为下拉式接受格式 value  label
      tagOptions.value = (res.data.data.tagList ?? []).map((data: string) => {
        return {
          value: data,
          label: data,
        }
      })
      categoryOptions.value = (res.data.data.categoryList ?? []).map((data: string) => {
        return {
          value: data,
          label: data,
        }
      })
    } else {
      message.error('加载选项失败：' + res.data.message)
    }
  } catch (e) {
    message.error('加载选项失败：' + e)
  }
}
// 图片编辑弹窗引用
const imageCropperRef = ref()
// AI 扩图弹窗引用
const imageOutPaintingRef = ref()

// 打开 AI 扩图弹窗
const doImagePainting = async () => {
  imageOutPaintingRef.value?.showModal()
}

// 编辑成功事件
const onImageOutPaintingSuccess = (newPicture: API.PictureVO) => {
  picture.value = newPicture
}

// 编辑图片
const doEditPicture = async () => {
  imageCropperRef.value?.openModal()
}

// 编辑成功事件
const onCropSuccess = (newPicture: API.PictureVO) => {
  picture.value = newPicture
}

/**
 * 提交表单
 * @param values
 */
const handleSubmit = async (values: any) => {
  console.log(values)
  const pictureId = picture.value.id
  if (!pictureId) {
    return
  }
  const res = await editPictureUsingPost({
    id: pictureId,
    spaceId: spaceId.value || picture.value?.spaceId, // 使用 spaceId 或图片的 spaceId
    ...values,
  })
  // 操作成功
  if (res.data.code === 0 && res.data.data) {
    message.success('创建成功')
    // 跳转到图片详情页
    router.push({
      path: `/picture/${pictureId}`,
    })
  } else {
    message.error('创建失败，' + res.data.message)
  }
}
//加载
onMounted(() => {
  getTagCateGoryOptions()
})
// 获取老数据
const route = useRoute()
const getOldPicture = async () => {
  // 获取到 id
  const id = route.query?.id
  if (id) {
    const res = await getPictureVoByIdUsingGet({
      id,
    })
    if (res.data.code === 0 && res.data.data) {
      const data = res.data.data
      picture.value = data
      pictureForm.name = data.name
      pictureForm.introduction = data.introduction
      pictureForm.category = data.category
      pictureForm.tags = data.tags

      // 如果图片有 spaceId 但当前页面没有 spaceId 参数，则从图片信息中获取空间信息
      if (data.spaceId && !spaceId.value) {
        console.log('从图片获取空间ID:', data.spaceId)
        // 手动获取空间信息
        const spaceRes = await getSpaceVoByIdUsingGet({
          id: data.spaceId,
        })
        console.log('获取空间信息结果:', spaceRes)
        if (spaceRes.data.code === 0 && spaceRes.data.data) {
          space.value = spaceRes.data.data
          console.log('从图片ID获取的空间信息:', space.value)
        }
      }
    }
  }
}
const space = ref<API.SpaceVO>()

// 获取空间信息
const fetchSpace = async () => {
  // 获取数据
  if (spaceId.value) {
    const res = await getSpaceVoByIdUsingGet({
      id: spaceId.value,
    })
    console.log('res:{}', res)
    if (res.data.code === 0 && res.data.data) {
      space.value = res.data.data
    }
  }
}

watchEffect(() => {
  fetchSpace()
})

onMounted(() => {
  getOldPicture()
})
</script>
<style scoped>
#addPicturePage {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.upload-form-container {
  display: flex;
  flex-direction: column;
  gap: 24px;
  transition: all 0.3s ease;
}

.upload-form-container.has-picture {
  flex-direction: row;
  align-items: flex-start;
}

.upload-section,
.edit-form,
.edit-bar {
  background-color: #fff;
  border: 1px solid #e8e8e8;
  border-radius: 4px;
  padding: 20px;
  margin-bottom: 20px;
}

.upload-section {
  flex: 1;
}

.edit-form {
  flex: 1;
  margin-top: 0;
}

.edit-bar {
  text-align: center;
}

.has-picture .upload-section,
.has-picture .edit-form {
  max-width: 50%;
  padding: 20px;
}
</style>


